package com.xfcycle.zebrabikegp.util;

import android.content.Context;

import com.xfcycle.zebrabikegp.assist.AppAssist;
import com.xfcycle.zebrabikegp.constant.SpConstant;
import com.xfcycle.zebrabikegp.constant.WebConstant;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 通过网络处理数据
 *
 * @author Wesley
 *         jdk 1.8  Android 21
 *         2017年3月1日
 */
public class HandleDataByWebUtil {

    private Context context;
    private static HandleDataByWebUtil handleDataByWebUtil;

    private HandleDataByWebUtil(Context context) {
        this.context = context;
    }

    public static HandleDataByWebUtil getInstance(Context context) {
        synchronized (HandleDataByWebUtil.class) {
            if (null == handleDataByWebUtil || !context.equals(handleDataByWebUtil.context)) {
                handleDataByWebUtil = new HandleDataByWebUtil(context);
            }
        }
        return handleDataByWebUtil;
    }

    /**
     * 利用Get请求通过网络获得json格式数据
     *
     * @param requestPath，格式为"/user"类
     * @param param，格式为"name1=value1&name2=value2"的形式
     * @return String，返回结果为一个json格式字符串
     */
    public String getJsonFromWebByGet(String requestPath, String param) {
        String result = "";
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer data_cache = new StringBuffer();

        try {
            //判断是否成功从文件中取到URL地址
            if (null == getUrlFromFile()) {
                return result;
            }

            //获取get请求 计算Authorization时需要的请求地址
            StringBuffer path = new StringBuffer().append(requestPath);
            if (null != param) {
                path = path.append("?").append(param);
            }

            StringBuffer urlNameString = getUrlFromFile()
                    .append(path);

            URL realUrl = new URL(urlNameString.toString());
            //获取和Url之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();

            //设置请求的通用属性
            if (!requestPath.contains("public")) {
                //判断该请求是否是public请求，不是，则需要验证请求的合法性
                connection.setRequestProperty("Authorization", getAuthorization("GET\n" + path));
            }

            //验证请求是否是同一个设备发出的,传入值为设备号
            connection.setRequestProperty("User-Agent", getPhoneUUID(context));

            //建立实际的连接
            connection.connect();

            //判断返回码获得相应的is流
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
            }
            br = new BufferedReader(new InputStreamReader(is));

            //接收返回的结果
            String line = "";
            while (null != (line = br.readLine())) {
                data_cache.append(line);
            }

            result = data_cache.toString();

            //关闭网络连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            result = "defeat";
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != br) {
                    br.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 利用Post请求通过网络获得请求数据
     *
     * @param requestPath，格式为"/user"类
     * @param param，格式为"name1=value1&name2=value2"的形式
     * @return String，返回结果为一个json格式字符串
     */
    public String getJsonFromWebByPost(String requestPath, String param) {
        String result = "";
        InputStream is = null;
        BufferedReader br = null;
        PrintWriter out = null;
        StringBuffer data_cache = new StringBuffer();

        try {

            //判断是否成功从文件中取到URL地址
            if (null == getUrlFromFile()) {
                return result;
            }

            String urlNameString = getUrlFromFile()
                    .append(requestPath)
                    .toString();

            URL realUrl = new URL(urlNameString);
            //获取和Url之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();

            //设置请求的通用属性
            if (!requestPath.contains("public")) {
                //判断该请求是否是public请求，不是，则需要验证请求的合法性
                connection.setRequestProperty("Authorization", getAuthorization("POST\n" + requestPath));
            }
            //验证请求是否是同一个设备发出的,传入值为设备号
            connection.setRequestProperty("User-Agent", getPhoneUUID(context));

            //发送Post请求必须设置如下两行
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());

            //发送请求参数
            if (null != param) {
                out.print(param);
            }

            out.flush();

            //判断返回码获得相应的is流
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
            }
            br = new BufferedReader(new InputStreamReader(is));

            //接收返回的结果
            String line = "";
            while (null != (line = br.readLine())) {
                data_cache.append(line);
            }

            result = data_cache.toString();

            //关闭网络连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            result = "defeat";
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != out) {
                    out.close();
                }
                if (null != br) {
                    br.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 利用put请求向服务器传递修改数据
     *
     * @param requestPath 格式为"/user"类
     * @param param       格式为"name1=value1&name2=value2"的形式
     * @return String 返回结果为一个json格式字符串
     */
    public String getJsonFromWebByPut(String requestPath, String param) {
        String result = "";
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer data_cache = new StringBuffer();

        try {

            //判断是否成功从文件中取到URL地址
            if (null == getUrlFromFile()) {
                return result;
            }

            //获取get请求 计算Authorization时需要的请求地址
            StringBuffer path = new StringBuffer().append(requestPath);
            if (null != param) {
                path = path.append("?").append(param);
            }

            StringBuffer urlNameString = getUrlFromFile()
                    .append(path);

            URL realUrl = new URL(urlNameString.toString());

            //获取和Url之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();

            //设置请求方式，唯一和Get请求不一样的地方
            connection.setRequestMethod("PUT");

            //设置请求的通用属性
            if (!requestPath.contains("public")) {
                //判断该请求是否是public请求，不是，则需要验证请求的合法性
                connection.setRequestProperty("Authorization", getAuthorization("PUT\n" + path));
            }

            //验证请求是否是同一个设备发出的,传入值为设备号
            connection.setRequestProperty("User-Agent", getPhoneUUID(context));

            //建立实际的连接
            connection.connect();

            //判断返回码获得相应的is流
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED) {
                is = connection.getInputStream();
            } else {
                is = connection.getErrorStream();
            }
            br = new BufferedReader(new InputStreamReader(is));

            //接收返回的结果
            String line = "";
            while (null != (line = br.readLine())) {
                data_cache.append(line);
            }

            result = data_cache.toString();

            //关闭网络连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            result = "defeat";
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != br) {
                    br.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取手机的UUID
     *
     * @param context 需要用到的上下文
     * @return 返回的UUID
     */
    private String getPhoneUUID(Context context) {
        String uuid = HandleDataBySharePreferencesUtil.getInstance(context).getDateFromSharePre(SpConstant.SP_NAME, SpConstant.PHONE_UUID_KEY);

        if (null == uuid) {
            //获取手机UUID
            GetUUIDUtil getUUIDUtil = GetUUIDUtil.getInstance(context);
            uuid = getUUIDUtil.getDevicesUUIDByMD5();

            //将其存储到sp中
            Map<String, String> spParams = new HashMap<>();
            spParams.put(SpConstant.PHONE_UUID_KEY, uuid);
            HandleDataBySharePreferencesUtil.getInstance(context).putDateIntoSharePre(SpConstant.SP_NAME, spParams);
        }
        return uuid;
    }

    /**
     * 得到配置文件中的网络请求地址 该配置文件存放在Assets文件夹下 路径为 app/src/main/assets
     */
    public StringBuffer getUrlFromFile() {
        StringBuffer baseURL = new StringBuffer();

        //判断当前是国服还是美服 默认美服
        String server_address;
        if (WebConstant.isCN) {
            server_address = "server_address_cn";
        } else {
            server_address = "server_address_us";
        }


        String value = HandleDataByFileUtil.getDatafromProperties(server_address, context);

        if (null == value) {
            return null;
        }

        baseURL.append("http://")
                .append(value);
        return baseURL;
    }

    /**
     * 获取签名字符串
     * 用于验证网络请求的路径有没有错误
     *
     * @param requestPath 需要验证的网络请求地址 即在地址栏中的地址，get和put包含参数 post没有参数
     * @return
     */
    public String getAuthorization(String requestPath) {

//        HandleDataBySharePreferencesUtil handleDateBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(context);
//        String uid = handleDateBySharePreferencesUtil.getDateFromSharePre(RootActivity.APP_INFO_SP_NAME, "uid");
//        String password = handleDateBySharePreferencesUtil.getDateFromSharePre(RootActivity.APP_INFO_SP_NAME, "password");
//        String key = EncryptStringUtil.getMd5(password) + "zebra";
//        String authorization = null;
//        try {
//            authorization = "ZB " + uid + ": " + EncryptStringUtil.String2Base64(EncryptStringUtil.String2HmacSHA1(requestPath, key));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        return "Bearer " + AppAssist.ApiToken;
    }
}
